from django.shortcuts import render, redirect
from django.contrib import messages
from django.views.decorators.http import require_POST
from .pinn import solve_dae_system
def index(request):
    return render(request, 'index.html')

def request(request):
    return render(request, 'solver.html')

def result1(request):
    return render(request, 'result1.html')
def result2(request):
    return render(request, 'result2.html')

def home(request):
    """主页面"""
    return render(request, 'solver.html')


@require_POST
def start_solving(request):
    """处理提交请求"""
    if request.session.get('is_processing', False):
        messages.warning(request, "正在处理上一个请求，请稍候...")
        return redirect('myweb:home')

    equations = request.POST.get('equations', '').strip()
    if not equations:
        messages.error(request, "方程不能为空")
        return redirect('myweb:home')

    # 存储数据到session
    request.session['equations'] = equations
    request.session['t_max'] = float(request.POST.get('t_max', 5.0))
    request.session['is_processing'] = True

    return redirect('myweb:processing')


def processing(request):
    """计算中页面"""
    if not request.session.get('is_processing', False):
        return redirect('myweb:home')

    # 实际计算（模拟耗时操作）
    try:
        results = solve_dae_system(
            request.session['equations'],
            request.session['t_max']
        )
        request.session['results'] = results
        return redirect('myweb:show_results')
    except Exception as e:
        messages.error(request, f"计算失败: {str(e)}")
        request.session['is_processing'] = False
        return redirect('myweb:home')


def show_results(request):
    """显示结果页面"""
    if 'results' not in request.session:
        return redirect('myweb:home')

    results = request.session.pop('results')
    request.session['is_processing'] = False

    return render(request, 'results.html', {
        'svg_plot': results['plot'],
        'table_data': results['table_data'],
        'variables': results['variables']
    })
